import { Router } from "express";
import klawSync from "klaw-sync";

const router = Router();
router.use("/api/search-folder", (req, res) => {
  let {
    body: { queryString },
  } = req;
  try {
    let files = [];
    try {
      let dirname = queryString
        .replace(/\\/g, "/")
        .split("/")
        .slice(0, -1)
        .join("/");
      let toPush = klawSync(dirname, { depthLimit: 0, nofile: true })
        .map((e) => e.path)
        .filter((e) => e.includes(queryString));
      files.push(...toPush);
    } catch (error) {
      //
    }
    try {
      let toPush = klawSync(queryString, { depthLimit: 0, nofile: true }).map(
        (e) => e.path
      );
      files.push(...toPush);
    } catch (error) {
      //
    }
    res.json(files.map((e) => e.replace(/\\/g, "/")));
  } catch (error) {
    res.json([]);
  }
});

export default router;
